import 'package:chat/model/message_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class FriendChatController extends GetxController {
  final RxList<Message> messages = <Message>[].obs;
  final RxBool showOther = false.obs;
  final RxBool showOptions = false.obs;
  final RxBool showImg = false.obs;
  final RxBool showPadding = true.obs;
  final FocusNode textFieldFocusNode = FocusNode();
  final RxString currentContact = 'seth.eth'.obs;
  final TextEditingController messageController = TextEditingController();
  final ScrollController scrollController = ScrollController();
  var keyboardHeight = 260.0.obs;
  final List<String> emojis = [
    '😀',
    '😃',
    '😄',
    '😁',
    '😆',
    '😅',
    '😂',
    '🤣',
    '😊',
    '😇',
    '🙂',
    '🙃',
    '😉',
    '😌',
    '😍',
    '🥰',
    '😘',
    '😗',
    '😙',
    '😚',
    '😋',
    '😛',
    '😝',
    '😜',
    '🤪',
    '🤨',
    '🧐',
    '🤓',
    '😎',
    '🤩',
    '🥳',
    '😏',
  ];

  @override
  void onInit() {
    super.onInit();
    loadMessages();
    // 监听焦点变化
    textFieldFocusNode.addListener(() {
      debugPrint('focus: ${textFieldFocusNode.hasFocus}');
      if (textFieldFocusNode.hasFocus) {
        // 当输入框获得焦点时，强制关闭其他面板
        if (!showOptions.value && !showImg.value) {
          showOther.value = true;
        }
      }
      uopdateShowPadding();
    });
  }

  void uopdateShowPadding() {
    if (showImg.value || showOptions.value || textFieldFocusNode.hasFocus) {
      showPadding.value = false;
    } else {
      showPadding.value = true;
    }
    debugPrint('showPadding: $showPadding');
  }

  @override
  void onClose() {
    debugPrint('onClose');
    messageController.dispose();
    scrollController.dispose();
    textFieldFocusNode.dispose();
    super.onClose();
  }

  void toggleAll() {
    showOther.value = false;
    showOptions.value = false;
    showImg.value = false;
    textFieldFocusNode.unfocus();
  }

  void loadMessages() {
    messages.assignAll([
      Message(
        id: '1',
        senderId: '1',
        senderName: 'seth.eth',
        senderAvatar: 'https://via.placeholder.com/50',
        content: 'Bro! you have to check this collection out',
        time: DateTime.now().subtract(const Duration(minutes: 30)),
        isMe: false,
      ),
      Message(
        id: '2',
        senderId: '2',
        senderName: 'Me',
        senderAvatar: 'https://via.placeholder.com/50',
        content: 'I have but i cant buy in now...',
        time: DateTime.now().subtract(const Duration(minutes: 25)),
        isMe: true,
      ),
      Message(
        id: '3',
        senderId: '2',
        senderName: 'Me',
        senderAvatar: 'https://via.placeholder.com/50',
        content: 'Is it gonna dip?',
        time: DateTime.now().subtract(const Duration(minutes: 5)),
        isMe: true,
      ),
    ]);
  }

  void toggleImg() {
    if (textFieldFocusNode.hasFocus) {
      if (showOther.value) {
        showOther.toggle();
      }
      if (showOptions.value) {
        showOptions.toggle();
      }
      if (showImg.value) {
        textFieldFocusNode.unfocus();
      } else {
        showImg.toggle();
        textFieldFocusNode.unfocus();
      }
    } else {
      if (showOptions.value) {
        showOptions.toggle();
      }
      showImg.toggle();
      if (textFieldFocusNode.hasFocus) {
        textFieldFocusNode.unfocus();
      }
    }
    scrollToBottom();
    uopdateShowPadding();
  }

  void toggleOptions() {
    if (textFieldFocusNode.hasFocus) {
      if (showOther.value) {
        showOther.toggle();
      }
      if (showImg.value) {
        showImg.toggle();
      }
      if (showOptions.value) {
        textFieldFocusNode.unfocus();
      } else {
        showOptions.toggle();
        textFieldFocusNode.unfocus();
      }
    } else {
      if (showImg.value) {
        showImg.toggle();
      }
      showOptions.toggle();
      if (textFieldFocusNode.hasFocus) {
        textFieldFocusNode.unfocus();
      }
    }
    scrollToBottom();
    uopdateShowPadding();
  }

  void sendMessage() {
    textFieldFocusNode.requestFocus();
    if (messageController.text.trim().isEmpty) return;

    final newMessage = Message(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      senderId: '2',
      senderName: 'Me',
      senderAvatar: 'https://via.placeholder.com/50',
      content: messageController.text,
      time: DateTime.now(),
      isMe: true,
    );

    messages.add(newMessage);
    scrollToBottom();
    messageController.clear();

    // 模拟回复
    Future.delayed(const Duration(seconds: 1), () {
      final replyMessage = Message(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        senderId: '1',
        senderName: 'seth.eth',
        senderAvatar: 'https://via.placeholder.com/50',
        content: 'Reply to your message',
        time: DateTime.now(),
        isMe: false,
      );
      messages.add(replyMessage);
      scrollToBottom();
    });
  }

  // 滚动到底部
  void scrollToBottom() {
    debugPrint('scrollToBottom${scrollController.hasClients}');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (scrollController.hasClients && messages.isNotEmpty) {
        debugPrint('scrollToBottom${scrollController.position.maxScrollExtent}');
        scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void sendMedia(MessageType type) {
    // 处理发送不同类型的媒体消息
    String content;
    switch (type) {
      case MessageType.image:
        content = '[Photo]';
        break;
      case MessageType.video:
        content = '[Video]';
        break;
      case MessageType.location:
        content = '[Location]';
        break;
      case MessageType.voice:
        content = '[Voice Message]';
        break;
      default:
        content = '';
    }

    final newMessage = Message(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      senderId: '2',
      senderName: 'Me',
      senderAvatar: 'https://via.placeholder.com/50',
      content: content,
      time: DateTime.now(),
      isMe: true,
      type: type,
    );

    messages.add(newMessage);
    showOptions.value = false;
  }
}
